<template>
  <a-form ref="formRef" v-bind="formAttr" :model="formState">
    <!-- <template #[key]="data" v-for="(item, key) in $slots">
      <slot :name="key" v-bind="data || {}"></slot>
    </template> -->
    <template v-for="column in cColumns" >
      <slot v-if="Object.keys($slots||{}).includes(column.name as any)" :name="column.name" 
      :column="column"
      :model="formState"
      ></slot>
      <a-form-item v-else v-bind="{...column}">
        <component
        :ref="(el: any)=>setComponentRef(el,column.name as any)"
        v-if="['Radio','Switch','Checkbox'].includes(column.component as any)"
        :is="ComponentsMap[column.component as any]"
        v-bind="{...column.componentProps}" v-model:checked="formState[column.name as any]"
        />       
        <component 
        :ref="(el: any)=>setComponentRef(el,column.name as any)"
        v-else
        :is="ComponentsMap[column.component as any]"
        v-bind="{...column.componentProps}" v-model:value="formState[column.name as any]"
        />
      </a-form-item>
    </template>
    <a-form-item v-if="schema?.showOk!==false || schema?.showReset!==false" :wrapper-col="{ span: 24 }">
      <a-button v-if="schema?.showOk!==false" :loading="loading" @click="handleSubmit" type="primary">
        {{ schema?.okText || '提交' }}
      </a-button>
      <a-button v-if="schema?.showReset!==false" style="margin-left: 12px;" @click="handleReset" type="primary">
        {{ schema?.resetText || '重置' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script setup lang="ts">
import { PropType, computed, onMounted, reactive, ref, useAttrs } from 'vue'
import { MFormItemType, MFormType } from './types'
import request from '/@/utils/request'
import { message } from 'ant-design-vue'
import { ComponentsMap } from './index'
import { isNumber } from 'lodash-es'
const attrs = useAttrs();
const componentRefMap = reactive({})
const setComponentRef = (el: any,name: string) =>{
  componentRefMap[name] = el
}
const props = defineProps({
  schema: {
    type: Object as PropType<MFormType>
  },
  model: {
    type: Object as PropType<any>
  }
})
const emits = defineEmits(['reset','ok','submit-success','submit-fail'])
const loading = ref(false)
const cColumns = computed<Array<MFormItemType>>(()=>{
  const mColumns = props.schema?.columns || []
  mColumns.forEach(column=>{
    if(column.labelWidth) {
      column.labelCol = {
        flex: isNumber(column.labelWidth)?column.labelWidth+'px': column.labelWidth
      }
    }
    if(column.component == 'Divider') {
      column.componentProps = {
        orientation: 'left',
        title: column.label,
        ...column.componentProps,
      }
      column.label = undefined;
      column.labelWidth = 0;
    }
  })
  return mColumns
})
const formAttr = computed(()=>{
  const res = {
    ...attrs
  }
  if(props.schema?.labelWidth) {
    res.labelCol = {
      flex: isNumber(props.schema?.labelWidth)?props.schema?.labelWidth+'px': props.schema?.labelWidth
    }
  }
  return res
})
/**
 * 获取默认值
 */
const getDefaultValue = (columns: Array<MFormItemType>) =>{
  const v = {}
  console.log('getDefaultValue',columns);
  
  columns.forEach(item=>{
    v[item.name as string] = item.defaultValue
  })
  return v;
}
const formState = reactive({
  ...getDefaultValue(cColumns.value),
  ...props.model,
})

const formRef = ref()
const regisiter = {
  // 设置提交按钮加载状态
  setLoading(mLoading: boolean){
    loading.value = mLoading;
  },
  // 获取表单组件
  getComponentRef(name: string){
    return componentRefMap[name]
  },
  // 设置表单值
  setFieldsValue(values: any){
    if(formState && values) {
      Object.keys(values).forEach(key=>{
        formState[key] = values[key]
      })
    }
  }
}
// 将formRef绑定到regisiter，以便defineExpose
const bindFormRef = () =>{
  Object.keys(formRef.value).forEach(key=>{
    regisiter[key] = formRef.value[key]
  })
}
// 提交数据
const handleSubmit = () =>{
  formRef.value.validate().then((values: any)=>{
    let fun = undefined;
    if(props.schema?.api && typeof props.schema?.api === 'string') {
      fun = (v: any) => {
        return request.post(props.schema?.api as any, v)
      }
    } else if(props.schema?.api && typeof props.schema?.api === 'function') {
      fun = props.schema?.api
    }
    if(fun) {
      loading.value = true;
      fun(values).then((res: any)=>{
        message.success('提交成功!!!')
        emits('submit-success',res)
      }).catch((e: any)=>{
        emits('submit-fail',e)
      }).finally(()=>{
        loading.value = false;
      })
    } else {
      emits('ok',values)
    }
  }).catch((e: any)=>{
    console.log(e)
  })
}
// 重置
const handleReset = () => {
  formRef.value.resetFields()
  emits('reset')
}
onMounted(()=>{
  bindFormRef()
  // console.log('fghghte');
  
  // console.log(ComponentsMap)
})
defineExpose(regisiter)
</script>
<style lang="less" scoped>

</style>